#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menuBar= this->menuBar();
    QMenu* menu = new QMenu("document");
    menuBar->addMenu(menu);
    QAction* action1 = new QAction("open");
    QAction* action2 = new QAction("save");
    menu->addAction(action1);
    menu->addAction(action2);
    this->setWindowTitle("memo pad");
    QFont font;
    font.setPixelSize(20);
    edit = new QPlainTextEdit(this);
    edit->setFont(font);
    this ->setCentralWidget(edit);
    connect(action1,&QAction::triggered,this,&MainWindow::handle1);
    connect(action2,&QAction::triggered,this,&MainWindow::handle2);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle1()
{
    QString path = QFileDialog::getOpenFileName(this);
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly))
    {
        statusBar->showMessage(path + "fail to open");
        return;
    }
    QString text = file.readAll();
    file.close();
    edit->setPlainText(text);

}
void MainWindow::handle2()
{
    QString path = QFileDialog::getSaveFileName(this);
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);
    QFile file(path);
    if(!file.open(QIODevice::WriteOnly))
    {
        statusBar->showMessage(path + "fail to open");
        return;
    }
    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());
    file.close();



}

